<template>
  <div class="fourth_panel_module">
    <el-table
      :data="fourthFormatedChannelData"
      size="mini"
      border
      height="100%"
      style="width: 100%"
      :span-method="computedSpanMethod"
      :cell-style="computeCellStyle"
    >
      <el-table-column
        v-for="(column, key) in fourthChannelDict"
        :key="key"
        :prop="key"
        :label="column"
      >
        <template v-if="key !== 'channel'" v-slot="scope">
          <el-input
            size="mini"
            v-model="fourthFormatedChannelData[scope.$index][key]"
            placeholder="请输入"
            :disabled="disabled"
            @blur="onInputChange(key, scope.$index)"
          />
        </template>
      </el-table-column>
    </el-table>
    <div class="module-content">
      <div class="operation-module">
        <div>
          <span>加载声延时</span>
          <el-select
            v-model="comboxValue.AAD1001"
            size="mini"
            :disabled="disabled"
            @change="onComboxChange"
          >
            <el-option
              v-for="option in comboxOptions.AAD1001"
              :key="option.Savetime"
              :label="option.Savetime"
              :value="option.Savetime"
            />
          </el-select>
        </div>
        <div class="buttons">
          <el-button
            size="mini"
            type="primary"
            :disabled="disabled || !limits.AAD_1"
            @click="computeByFormula"
          >
            计算结果
          </el-button>
          <el-upload
            class="upload-demo"
            action=""
            accept=".xls, .xlsx, .csv"
            :disabled="disabled || !limits.AAD_2"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="readLocaleExcel"
          >
            <el-button size="mini" type="primary" :disabled="disabled || !limits.AAD_2">
              导入数据
            </el-button>
          </el-upload>
        </div>
      </div>
      <task-tab
        ref="tab"
        :settings="fourthChannelSettings"
        :disabled="disabled"
        :markedSettings="markedSettings"
      />
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Getter } from 'vuex-class'
import { Component, Prop, Watch, Ref } from 'vue-property-decorator'
import TaskTab from '@/views/dashboard/compoents/TaskTab.vue'
import {
  fourthChannelDict,
  fourthChannelTableData,
  fourthChannelSettings,
  fourth_CSV_KEYS_COMPARSION
} from '../utils/params'
import {
  FormatChannelData,
  FillInChannelData,
  GetComboxOptions,
  ComboxOptionsDict,
  FillInTaskTabData,
  CaptureChannelData,
  TransferCnKeyToEnKey
} from '@/utils/precedure'
import { AAD_ComputeByFormula } from '@/api/procedure'
import { AxiosResponse } from 'axios'
import XLSX from 'xlsx'
import { Dictionary } from '@/interface/Basic'
import { deepClone } from '@/utils/specificFunc'
@Component({
  components: {
    TaskTab
  }
})
class FourthPanel extends Vue {
  @Getter('theme') theme!: 'dark' | 'light'
  @Ref() tab!: { captureSettings: () => Dictionary<string> }
  @Prop({ required: true }) records!: Dictionary<string>
  @Prop({ default: true }) disabled!: boolean
  @Prop({ required: true }) limits!: Dictionary<boolean>
  meter: string = ''
  fourthChannelDict = fourthChannelDict
  fourthChannelSettings = fourthChannelSettings
  fourthChannelTableData = fourthChannelTableData
  fourthFormatedChannelData: Dictionary<string>[] = []
  comboxOptions: ComboxOptionsDict = {}
  comboxValue: Dictionary<string> = {
    AAD1001: ''
  }
  markedSettings: Dictionary<string[]> = {
    isWarning: []
  }
  @Watch('records', { deep: true })
  records_handler(newVal: Dictionary<string>) {
    this.fourthFormatedChannelData = FormatChannelData(
      FillInChannelData(this.fourthChannelTableData, newVal),
      Object.keys(this.fourthChannelDict)
    )
    this.fourthChannelSettings = FillInTaskTabData(this.fourthChannelSettings, newVal)
  }
  mounted() {
    this.meter = this.$route.params.meterid
    this.fourthFormatedChannelData = FormatChannelData(
      this.fourthChannelTableData,
      Object.keys(this.fourthChannelDict)
    )
    GetComboxOptions(this.meter).then(res => {
      this.comboxOptions = deepClone(res)
    })
  }
  computedSpanMethod({ column, rowIndex }: any) {
    if (column.property === 'Actual_Sound_Path') {
      if (rowIndex % 2 === 0) {
        return {
          rowspan: 2,
          colspan: 1
        }
      } else {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    }
  }
  computeCellStyle(e: { rowIndex: number; column: any }) {
    const { rowIndex, column } = e
    const _keys = Object.keys(this.fourthChannelTableData[rowIndex])
    if (
      this.markedSettings.isWarning.includes(_keys[_keys.length - 1]) &&
      column.property === 'Actual_Sound_Path'
    ) {
      return {
        backgroundColor: this.theme === 'dark' ? '#FCDC33' : '#FCDF2D'
      }
    }
  }
  onComboxChange(e: string) {
    const options = this.comboxOptions.AAD1001.find(item => item.Savetime === e)
    if (!options) return
    Object.keys(options.Value).forEach((key, index) => {
      const frame = this.fourthFormatedChannelData.slice(index, index + 1).map(sub_obj => {
        sub_obj.AAD301 = options.Value[key]
        return sub_obj
      })
      this.fourthFormatedChannelData.splice(index, 1, ...frame)
    })
  }
  onInputChange(key: string | number, index: number) {
    if (key === 'AAD401') {
      this.fourthFormatedChannelData[index % 2 === 0 ? index + 1 : index - 1][key] =
        this.fourthFormatedChannelData[index][key]
    }
  }
  CaptureTotalParams() {
    const copiedRecords = deepClone(this.records)
    // fourthChannelSettings
    // fourthFormatedChannelData
    const captureResult = {
      ...this.tab.captureSettings(),
      ...CaptureChannelData(this.fourthFormatedChannelData, this.fourthChannelTableData)
    }
    Object.keys(captureResult).forEach(key => {
      if (key !== 'static') {
        copiedRecords[key] = captureResult[key]
      }
    })
    return copiedRecords
  }
  readLocaleExcel(file: { name: string; raw: File }) {
    const fileReader = new FileReader()
    fileReader.onload = ev => {
      try {
        const data = ev.target!.result
        const workbook = XLSX.read(data, {
          type: 'binary',
          cellDates: true,
          codepage: 936
        })
        const wsname = workbook.SheetNames
        const ws: Dictionary<string>[] = XLSX.utils.sheet_to_json(workbook.Sheets[wsname[0]], {
          defval: null
        })
        const origin = ws[ws.length - 1]
        const res = TransferCnKeyToEnKey(fourth_CSV_KEYS_COMPARSION, origin)
        this.fourthFormatedChannelData = FormatChannelData(
          FillInChannelData(this.fourthChannelTableData, res),
          Object.keys(this.fourthChannelDict)
        )
        this.fourthChannelSettings = FillInTaskTabData(this.fourthChannelSettings, res)
      } catch {
        return false
      }
    }
    fileReader.readAsBinaryString(file.raw)
  }
  computeByFormula() {
    const options = this.comboxOptions.AAD1001.find(
      item => item.Savetime === this.comboxValue.AAD1001
    )
    if (!options) return
    AAD_ComputeByFormula({ ...this.CaptureTotalParams(), ...options.Value }).then(
      (res: AxiosResponse<{ ReturnData: { result: Dictionary<string>; Nocount: string[] } }>) => {
        const { result, Nocount } = res.data.ReturnData
        this.markedSettings.isWarning = Nocount
        this.fourthFormatedChannelData = FormatChannelData(
          FillInChannelData(this.fourthChannelTableData, result),
          Object.keys(this.fourthChannelDict)
        )
        // 捕获修改过的数据，与接口返回的数据合并后更新数据
        const origin: Dictionary<string> = { ...this.tab.captureSettings(), ...result }
        this.fourthChannelSettings = FillInTaskTabData(this.fourthChannelSettings, origin)
      }
    )
  }
}
export default FourthPanel
</script>

<style lang="less" scoped>
@import '~@/styles/theme.less';
@import '~@/styles/layout.less';
.fourth_panel_module {
  height: 100%;
  #flex(row, flex-start, space-between);
  .el-table,
  .module-content {
    flex: 1;
  }
  .module-content {
    box-sizing: border-box;
    margin-left: 15px;
    padding-left: 15px;
    border-left: solid 1px;
    height: 350px;
    overflow: auto;
    #flex(column, center, flex-start);
    #color(border-left-color, --primary-border-color);
    .operation-module {
      box-sizing: border-box;
      padding-bottom: 10px;
      width: 100%;
      border-bottom: solid 1px;
      #flex(row, center, space-between);
      #color(border-bottom-color, --primary-border-color);
      span {
        font-size: 14px;
        margin-right: 10px;
      }
      .buttons {
        flex: 1;
        #flex(row, center, flex-end);
        .el-button {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
